package com.steven.ourcontest.main.view

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.steven.ourcontest.R
import com.steven.ourcontest.app.AppRouter
import com.steven.ourcontest.base.BaseFragment
import com.steven.ourcontest.main.adapter.RecruitTeamAdapter
import com.steven.ourcontest.main.bean.Top5TeamBannerInfo
import com.steven.ourcontest.main.viewmodel.MainViewModel
import com.steven.ourcontest.me.widget.GlideRoundTransform
import com.steven.ourcontest.net.NetConstants
import com.steven.ourcontest.utils.Identity
import kotlinx.android.synthetic.main.fragment_main.*

class MainFragment : BaseFragment() {

    private val mAdapter by lazy {
        context?.let { RecruitTeamAdapter(it) }
    }
    private val mainViewModel: MainViewModel by viewModels()

    override fun getViewId(): Int {
        return R.layout.fragment_main
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        rv_recruit_team?.adapter = mAdapter
        xbanner?.loadImage { _, model, itemView, _ ->
            if (model is Top5TeamBannerInfo) {
                val tvTeamName = itemView.findViewById<TextView>(R.id.tv_team_name)
                val tvPreviews = itemView.findViewById<TextView>(R.id.tv_pageViews)
                val tvLeaderName = itemView.findViewById<TextView>(R.id.tv_leader_name)
                val ivIcon = itemView.findViewById<ImageView>(R.id.iv_icon)
                val tvStatus = itemView.findViewById<TextView>(R.id.tv_status)
                val tvMatch = itemView.findViewById<TextView>(R.id.tv_match)
                val tvMember = itemView.findViewById<TextView>(R.id.tv_member)
                val tvUsertype = itemView.findViewById<TextView>(R.id.tv_userType)
                tvTeamName?.text = model.team.teamName
                tvPreviews?.text = model.team.pageViews.toString()
                tvLeaderName?.text = model.team.uname
                Glide.with(this)
                    .load(NetConstants.ICON_BASE_URL + model.team.iconUrl)
                    .dontAnimate()
                    .error(R.drawable.ic_avatar)
                    .apply(
                        RequestOptions.bitmapTransform(GlideRoundTransform(context, 10))
                    ).into(ivIcon)
                when (model.team.status) {
                    0 -> {
                        tvStatus?.text = "招募状态:关闭"
                    }
                    1 -> {
                        tvStatus?.text = "招募状态:开启"
                    }
                }
                tvMatch?.text = "面向竞赛:${model.team.matchName}"
                tvMember?.text = "队伍成员:${model.team.memberNum}人"
                tvUsertype?.text = when (model.team.userType) {
                    Identity.TEACHER.value -> {
                        tvUsertype?.isVisible = true
                        if (model.sameSchool) {
                            "本校老师"
                        } else {
                            "老师"
                        }
                    }
                    Identity.STUDENT.value -> {
                        tvUsertype?.isVisible = true
                        if (model.sameSchool) {
                            "本校学生"
                        } else {
                            "学生"
                        }
                    }
                    Identity.ADMIN.value -> {
                        tvUsertype?.isVisible = true
                        if (model.sameSchool) {
                            "本校管理员"
                        } else {
                            "管理员"
                        }
                    }
                    else -> {
                        tvUsertype?.isVisible = false
                        ""
                    }
                }
            }
        }
        smart_refresh?.setEnableLoadMore(true)
        smart_refresh?.setEnableRefresh(true)
        smart_refresh?.setRefreshHeader(ClassicsHeader(context))
        smart_refresh?.setRefreshFooter(ClassicsFooter(context))
        initListener()
        mainViewModel.queryTop5Team()
        mainViewModel.queryRecruitData()
    }

    private fun initListener() {
        mainViewModel.recruitTeam.observe(viewLifecycleOwner, Observer {
            if (smart_refresh?.isLoading == true) {
                smart_refresh?.finishLoadMore()
            }
            if (smart_refresh?.isRefreshing == true) {
                smart_refresh?.finishRefresh()
            }
            if (it != null) {
                mAdapter?.submitData(it.data)
            }
        })
        iv_message?.setOnClickListener {
            context?.let { it1 -> AppRouter.openTeamApplicationActivity(it1) }
        }
        mainViewModel.top5Team.observe(viewLifecycleOwner, Observer {
            if (smart_refresh?.isRefreshing == true) {
                smart_refresh?.finishRefresh()
            }
            val bannerList = ArrayList<Top5TeamBannerInfo>()
            if (it.inSchoolData?.isNotEmpty() == true || it.notInSchoolData.isNotEmpty()) {
                tv_hot_team?.isVisible = true
                xbanner?.isVisible = true
                it.inSchoolData?.forEach { detail ->
                    bannerList.add(Top5TeamBannerInfo(detail, sameSchool = true))
                }
                it.notInSchoolData.forEach { detail ->
                    if (bannerList.size >= 5) {
                        return@forEach
                    }
                    bannerList.add(Top5TeamBannerInfo(detail))
                }
                xbanner?.setBannerData(R.layout.item_top5_team, bannerList)
            } else {
                tv_hot_team?.isVisible = false
                xbanner?.isVisible = false
            }
        })
        xbanner?.setOnItemClickListener { _, model, _, _ ->
            if (context == null)
                return@setOnItemClickListener
            if (model is Top5TeamBannerInfo && context != null) {
                AppRouter.openTeamDetailActivity(requireContext(), model.team.teamId)
            }
        }
        edit_container?.setOnClickListener {
            context?.let { it1 -> AppRouter.openSearchMatchActivity(it1) }
        }
        smart_refresh?.setOnLoadMoreListener {
            mainViewModel.queryRecruitData()
        }
        smart_refresh?.setOnRefreshListener {
            mainViewModel.queryTop5Team()
            mainViewModel.queryRecruitData()
        }
    }

    override fun onResume() {
        super.onResume()
        xbanner?.startAutoPlay()
    }

    override fun onPause() {
        xbanner?.stopAutoPlay()
        super.onPause()
    }
}